package org.dtrd.modules.questionnaire.controller;


import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.StrUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.dtrd.base.BaseController;
import org.dtrd.common.api.vo.Result;
import org.dtrd.config.system.Constant;
import org.dtrd.config.system.Constant.DiagnoseStatus;
import org.dtrd.modules.base.service.BaseCommonService;
import org.dtrd.modules.patient.service.IDtrdEntRdPatientService;
import org.dtrd.modules.questionnaire.entity.bean.*;
import org.dtrd.modules.questionnaire.service.IDtrdEntQuestionnaireRdLifewayService;
import org.dtrd.modules.questionnaire.service.IDtrdEntRdQuestionnaireRdVersionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;

import static org.dtrd.common.constant.CommonConstant.*;
import static org.dtrd.config.system.SystemState.ResponseState.*;

/**
 * <p>
 * 调查问卷 前端控制器
 * </p>
 *
 * @author QR
 * @since 2022-02-15
 */
@Api(tags = "患者建档及逆转问卷")
@RestController
@RequestMapping("/archive/")
@Slf4j
public class ArchiveController extends BaseController {

    @Autowired
    private IDtrdEntRdQuestionnaireRdVersionService questionnaireService;
    @Autowired
    private IDtrdEntQuestionnaireRdLifewayService lifewayService;
    @Autowired
    private BaseCommonService baseCommonService;
    @Autowired
    private IDtrdEntRdPatientService patientService;

    @ApiOperation(value = "获取手机端建档首页信息", response = ArchiveHomePageInfo.class)
    @GetMapping("index")
    public Result<?> getPhoneArchiveInfo(@RequestParam("patientId") Integer patientId) {
        ArchiveHomePageInfo info = patientService.getPatientArchiveHomePageInfo(patientId);
        String logContent = String.format("获取手机端建档首页信息, 患者id: %s", patientId);
        baseCommonService.addLog(logContent, OPERATE_TYPE_QUERY);
        return Result.OK(info);
    }

    @ApiOperation(value = "保存患者建档基本信息")
    @PostMapping("basic/save")
    public Result<?> saveOrUpdatePatientBasicInfo(@RequestBody @Validated PatientBasicInfo dto) {
        // 确诊有糖尿病时 判断糖尿病类型 和 确诊时间
        if (dto.getDiabetesDiagnosis() == Constant.DiagnoseStatus.HAD_DIAGNOSED.getType()) {
            if (dto.getDiabetesType() == null || dto.getDiabetesDiagnosisDate() == null) {
                return error(STATE_PARAMS_MISSING);
            }
        } else if (dto.getDiabetesDiagnosis().equals(Constant.DiagnoseStatus.UNDIAGNOSED.getType())) {
            // 未确诊糖尿病类型不设置
            dto.setDiabetesType(null);
        }

        boolean result = questionnaireService.saveQuestionnaireInfo(dto);
        String logContent = String.format("保存患者建档基本信息, 填写问卷人: %s", dto.getName());
        baseCommonService.addLog(logContent, OPERATE_TYPE_SAVE_OR_UPDATE);
        return result ? Result.OK("保存成功") : error(STATE_OPERATION_FAILURE);
    }

    @ApiOperation(value = "获取患者建档基本信息", response = PatientBasicInfo.class)
    @GetMapping("basic/get")
    public Result<?> getPatientBasicInfo(@RequestParam("patientId") Integer patientId) {
        if (patientId == null) {
            return Result.OK(new PatientBasicInfo());
        }
        PatientBasicInfo basicInfo = questionnaireService.getPatientBasicInfo(patientId);
        String logContent = String.format("获取患者建档基本信息, 患者id: %d", patientId);
        baseCommonService.addLog(logContent, OPERATE_TYPE_SAVE_OR_UPDATE);
        return Result.OK(basicInfo);
    }

    @ApiOperation(value = "获取患者档案详情信息", response = PatientDetailInfo.class)
    @GetMapping("detail/get")
    public Result<?> getPatientDetailInfo(@RequestParam("patientId") Integer patientId) {
        if (patientId == null) {
            return Result.OK(new PatientDetailInfo());
        }
        PatientDetailInfo detailInfo = questionnaireService.getPatientDetailInfo(patientId);
        String logContent = String.format("获取患者档案详情信息, 患者id: %d", patientId);
        baseCommonService.addLog(logContent, OPERATE_TYPE_QUERY);
        return Result.OK(detailInfo);
    }

    @ApiOperation("保存患者建档详情信息")
    @PostMapping("detail/save")
    public Result<?> saveOrUpdatePatientDetail(@RequestBody PatientDetailInfo info) {
        boolean result = questionnaireService.saveOrUpdatePatientDetail(info);
        String logContent = String.format("保存患者档案详情信息, 患者id: %d", info.getPatientId());
        baseCommonService.addLog(logContent, OPERATE_TYPE_SAVE_OR_UPDATE);
        return result ? Result.OK() : error(STATE_OPERATION_FAILURE);
    }

    @ApiOperation(value = "查询调查问卷详情", response = QuestionnaireRdVersionDetail.class)
    @GetMapping("reverse/get")
    public Result<?> getQuestionnaireReverse(@RequestParam Integer patientId) {
        QuestionnaireRdVersionDetail info = questionnaireService.getQuestionnaireReversion(patientId);
        String logContent = String.format("查询逆转调查问卷详情，查询查询患者id：%d", patientId);
        baseCommonService.addLog(logContent, OPERATE_TYPE_QUERY);
        return Result.OK(info);
    }

    private final static int COMPLICATION = 1;

    @ApiOperation(value = "提交逆转调查问卷", notes = "返回结果：0-不符合，1～4代表符合情况的1～4")
    @PostMapping("reverse/commit")
    public Result<?> saveQuestionnaireReverse(@RequestBody QuestionnaireRdVersionDetail dto) {
        // 基础信息
        if (StrUtil.isBlank(dto.getName())
                || dto.getSex() == null
                || dto.getDiabetesDiagnosis() == null
                || dto.getPatientId() == null
                || dto.getPhone() == null) {
            return error(STATE_PARAMS_MISSING);
        }
        if (!Validator.isMobile(dto.getPhone())) {
            log.info("ArchiveController.saveQuestionnaireReverse 用户id: {}, 填写手机号格式错误:{}", dto.getPatientId(), dto.getPhone());
            return Result.error("手机号格式错误");
        }
        if (Objects.equals(dto.getDiabetesDiagnosis(), DiagnoseStatus.HAD_DIAGNOSED.getType())) {
            // 确诊有糖尿病
            if (dto.getDiabetesType() == null || dto.getDiabetesDiagnosisDate() == null || dto.getHeight() == null ||
                    dto.getWeight() == null || dto.getWaistline() == null || dto.getCPeptide() == null || dto.getCPeptide2h() == null) {
                return error(STATE_PARAMS_MISSING);
            }
            // 有并发症
            if (Objects.equals(dto.getDiabetesComplication(), COMPLICATION)
                    && StrUtil.isBlank(dto.getDiabetesComplicationSymptom())) {
                return error(STATE_PARAMS_MISSING);
            }
        }

        Integer result = questionnaireService.saveQuestionnaireReversion(dto);
        String logContent = String.format("新增或修改逆转调查问卷, 填写问卷人: %s", dto.getName());
        baseCommonService.addLog(logContent, OPERATE_TYPE_SAVE_OR_UPDATE);
        return Result.OK(result);
    }

    @ApiOperation(value = "获取生活方式调查问卷", response = QuestionnaireLifewayDetail.class)
    @GetMapping("lifeway/get")
    public Result<?> getQuestionnaireLifeway(@RequestParam Integer patientId) {
        QuestionnaireLifewayDetail detail = lifewayService.getQuestionnaireRdLifeway(patientId);
        String logContent = String.format("获取生活方式调查问卷, 患者id: %d", patientId);
        baseCommonService.addLog(logContent, OPERATE_TYPE_QUERY);
        return Result.OK(detail);
    }

    @ApiOperation("保存生活方式调查问卷")
    @PostMapping("lifeway/commit")
    public Result<?> saveOrUpdateQuestionnaireLife(@RequestBody QuestionnaireLifewayDetail dto) {
        String input = dto.getInput();
        if (dto.getPatientId() == null
                || StrUtil.isBlank(input)) {
            return error(STATE_PARAMS_MISSING);
        }
        String[] answers = input.split(",");
        if (answers.length != Constant.QUESTIONNAIRE_LIFEWAY_PROBLEMS) {
            return error(STATE_PARAMS_ERROR);
        }
        boolean result = lifewayService.saveOrUpdateQuestionnaireRdLifeway(dto);
        String logContent = String.format("保存生活方式调查问卷, 患者id: %d", dto.getPatientId());
        baseCommonService.addLog(logContent, OPERATE_TYPE_ADD);
        return result ? Result.OK() : error(STATE_OPERATION_FAILURE);
    }

//    // TODO 并发症问卷
//    @ApiOperation(value = "获取患者的并发症问卷", notes = "尚未完成")
//    @GetMapping("complication/get")
//    public Result<?> getQuestionnaireComplication(@RequestParam Integer patientId){
//        String logContent = String.format("获取患者的并发症调查问卷, 患者id: %d", patientId);
//        baseCommonService.addLog(logContent, OPERATE_TYPE_QUERY);
//        return Result.OK();
//    }
//
//    @ApiOperation(value = "保存患者并发症问卷", notes = "尚未完成")
//    @PostMapping("complication/commit")
//    public Result<?> saveOrUpdateQuestionComplication(){
//        String logContent = String.format("保存患者并发症调查问卷");
//        baseCommonService.addLog(logContent, OPERATE_TYPE_ADD);
//        return Result.OK();
//    }
}
